package com.wanghlme.day25.dom;

import com.wanghlme.day25.pojo.Student;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class DomParse {
    public List<Student> parseXml() {
        List<Student> list = new ArrayList<>();
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();//获得Dom解析器工厂
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();//获得Dom解析器
            InputStream inStream = DomParse.class.getClassLoader().getResourceAsStream("data.xml");
            Document document = builder.parse(inStream);//将文件加载到内存中，获得对应的Document
            NodeList nodeList = document.getElementsByTagName("stu");//获得所有的stu子节点的集合
            //对集合遍历,遍历过程中,解析子节点name,weapon的内容
            for (int i = 0; i < nodeList.getLength(); i++) {
                Element node = (Element) nodeList.item(i);//获取当前节点
                String id = node.getAttribute("id");//获取stu节点的id属性
                Element nameEle = (Element) node.getElementsByTagName("name").item(0);//获取唯一的name子节点
                //nameEle.getFirstChild():取出文本节点，文本本身也是一个节点
                String name = nameEle.getFirstChild().getNodeValue();//取出文本节点的文本内容
                Element weaponEle = (Element) node.getElementsByTagName("weapon").item(0);
                String weapon = weaponEle.getFirstChild().getNodeValue();
                Student stu = new Student(id, name, weapon);
                list.add(stu);
            }
        } catch (DOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }
}
